#coding:utf-8
"""
Auth: 张宇飞(zhangyufei49@163.com)
Date: 2017-04-13
Desc: 用来打印带颜色的日志
"""

BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
PURPLE = 35
CYAN = 36
WHITE = 37

color_dict = {
    "black": BLACK,
    "red": RED,
    "green": GREEN,
    "yellow": YELLOW,
    "blue": BLUE,
    "purple": PURPLE,
    "cyan": CYAN,
    "white": WHITE,
}


class ColorPrint(object):
    def __init__(self):
        super(ColorPrint, self).__init__()

    def print_text(self, color, text, start=0, end=0):
        line = text.strip()
        if start < 0:
            start = 0
        if end < start:
            end = start + 1

        # 处理颜色参数异常
        if type(color) == str:
            color = color_dict.get(color.lower(), RED)
        elif type(color) == int:
            if color < BLACK or color > WHITE:
                color = RED
        else:
            color = RED

        # 打印
        if start == end:
            print("\033[;%dm%s\033[0m" % (color, line))
        else:
            print("%s\033[;%dm%s\033[0m%s" %
                  (line[:start], color, line[start:end], line[end:]))
